<?php

/**
 * 用户订单控制器
 * @author [杨伍]
 */
class Order extends Web_Controller
{
    public $bser_url= null;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Order_model', 'order_model');
        $this->load->model('Orderdetail_model');
        $this->load->model('User_model');
        $this->load->model('Activity_model');
        $this->load->model('Address_model');
        $this->load->helper('jsontoarray');
        $this->load->helper('redis');
        $this->base_url = $this->config->item('base_url');
    }

    /**
     * [shopingcat 购物车]
     * @return [type] [description]
     */
    public function shoppingcar(){
        $user = $this->userSession(false);
        $data['user'] = $user;
        $data['base_url'] = $this->config->item('base_url');
        $data['base_url'] = $this->base_url;
        $data['goodsid'] = $this->input->get('goodsid');
        $this->loadView('header', $data);
        $this->loadView('shop_car');
    }
    /**
     * [userOrders 用户订单详情]
     */
    public function  userOrders()
    {
        $user = $this->userSession(true, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        
        $order = $this->order_model->getOrderByUid($user->uid);
        $time_now = time();
        $tmp = array();
        foreach ($order as $value) {
            $tmp[] = $value['order_id'];           
        }
        $datas['data'] = array();
        if (!empty($tmp)) {
            $info = $this->Orderdetail_model->getOrderDetail($tmp);//订单详情
             //数据重构
            foreach ($order as $value) {
                $detail = array();
                foreach ($info as $v) {
                    if ($value['order_id'] == $v['order_id']) {
                        //详情按产品类别分组
                        if(array_key_exists($v['goods_id'], $detail))
                        {
                            $detail[$v['goods_id']]['amount'] += $v['amount'];
                        }
                        else
                        {
                            $img = img_jsons_to_array($v['banner_img']);
                            $detail[$v['goods_id']] = array(
                                'orderid' => $v['order_id'],
                                'goodsname' => $v['name'],
                                'other_name' => $v['other_name'],
                                'price' => $v['price'],
                                'amount' => $v['amount'],
                                'urlimg'=> '/static/upload/goods/'.$img['img_path'][0],
                                'imgname' => $img['img_name'][0],
                            );
                        }
                    }
                }                
                $datas['data'][] = array(
                    'orderid' => $value['order_id'],
                    'status'  => ($value['status'] == 3 && $time_now >= $value['create_time'] + 1800) ? 4 : $value['status'],//避免超时检测的时间差，采用下单时间跟当前时间比较来定义订单状态
                    'price'   => $value['price'],
                    'amount'  => $value['amount'],
                    'create_time' => $value['create_time'],
                    'detail'  => $detail,
                );
            }
        }
        $datas['title'] = '我的订单列表';
        $datas['base_url'] = $this->base_url;
        $datas['user'] = $user;
        $this->loadView('header', $datas);
        $this->loadView('my_order');
    }

    //订单记录
    public function orderinfo()
    {
        $user = $this->userSession(true, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        $orderid = $this->input->get('orderid');//订单id
        // $status = $this->input->get('status');//订单状态
        if( ! ctype_digit($orderid)){
            header('Location:'.$this->base_url.'home/order/userorders'); return;
        }
        $orderData = $this->order_model->getOrderByOrderid($orderid);
        if($user->uid != $orderData['uid']){
            header('Location:'.$this->base_url.'home/order/userorders'); return;
        }
        
        if($this->isWeChat() && $this->getOpenidFromSession() === null)
        {
            //重定向微信授权获取openid
            $url = urlencode($this->config->item('base_url') . '?from=1' . '&order_id=' . $orderid);
            $wechatRedirectUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb39298479fdd6af3&redirect_uri=' . $url . '&response_type=code&scope=snsapi_base#wechat_redirect';
            header('Location:' . $wechatRedirectUrl);return;
        }

        $orderData['detail'] = array();
        $time_now = time();
        if(!empty($orderData))
        {
            $orderData['status'] = ($orderData['status'] == 3 && $time_now >= $orderData['create_time'] + 1800) ? 4 : $orderData['status'];//避免超时检测的时间差，采用下单时间跟当前时间比较来定义订单状态
            $orderData['left_time'] = 30*60 - (time() - $orderData['create_time']);//剩余时间=30分钟 - 已过时间
            $info = $this->Orderdetail_model->getOrderDetailByOrderid($orderid);
            if(!empty($info))
            {
                //从组数据
                foreach ($info as $k => $v) 
                {
                    if(array_key_exists($v['goods_id'], $orderData['detail']))
                    {
                        $orderData['detail'][$v['goods_id']]['amount'] += $v['amount'];
                    }
                    else
                    {
                        $activity = $this->Activity_model->getActivitysById($v['activity_id']);
                        $img = img_jsons_to_array($v['banner_img']);
                        $orderData['detail'][$v['goods_id']] = array(
                            'goods_name'  => $v['name'],
                            'img_path'    => '/static/upload/goods/'.$img['img_path'][0],
                            'img_name'    => $img['img_name'][0],
                            'price'       => $v['price'],
                            'amount'      => $v['amount'],
                            'other_name'  => $v['other_name'],
                            'activity_desc'    => empty($activity['activity_desc']) ? '' : $activity['activity_desc']
                            );
                    }
                }
            }
        }else{
           header('Location:'.$this->base_url.'home/order/userorders'); return; 
        }
        $data['price'] = $orderData['price'];//总价
        $data['data'] = $orderData;//详细数据
        $data['base_url'] = $this->base_url;
        $data['order_id'] = $orderid;
        $data['openid'] = $this->session->openid;//用于判断是支付宝扫码进入还是微信扫码进入
        $data['user'] = $user;
        $status = $orderData['status'];
        if(isset($status) && $status==3){
            $this->loadView('header', $data);
            $this->loadView('confirm_order');
        }else{
            $this->loadView('header', $data);
            $this->loadView('detail_order2');
        }
    }

    /**
     * 进入订单填写页
     * @return [type] [description]
     */
    public function submitorder(){
        //登录后才能进入
        $user = $this->userSession(true, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

        if($this->isWeChat() && $this->getOpenidFromSession() === null)
        {
            //重定向微信授权获取openid
            $url = urlencode($this->config->item('base_url') . '?from=2' . '&data=' . $this->input->get('data'));
            $wechatRedirectUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb39298479fdd6af3&redirect_uri=' . $url . '&response_type=code&scope=snsapi_base#wechat_redirect';
            header('Location:' . $wechatRedirectUrl);return;
        }

        $orderData = json_decode(urldecode($this->input->get("data")));
        if($orderData == null)
        {
            echo '商品信息为空';
            return;
        }
        //获取该用户的默认收货地址
        $defaultAddressInfo= $this->User_model->getDefaultAddressInfoByUid($user->uid);
        if(! empty($defaultAddressInfo))
        {
            $this->load->model('Zone_model');
            $pre_address = $this->Zone_model->getZonesStringById($defaultAddressInfo['district']);
            $defaultAddressInfo['full_address'] = $pre_address . $defaultAddressInfo['address'];//详细地址
        }
        //获取所有goods_id对应的商品信息
        $this->load->model('Goods_model');
        $goodsInfo = array();
        $price = 0;//计算订单总价
        foreach ($orderData as $key => $value) {
            $goods = $this->Goods_model->getGoodsById($value->goods_id);
            if(! empty($goods) && $value->quantity > 0)
            {
                $img = img_jsons_to_array($goods['banner_img']);
                $img_path = ! empty($img['img_path'][0])?$img['img_path'][0]:'';
                $img_name = ! empty($img['img_name'][0])?$img['img_name'][0]:'';
                $goods['img_path'] = '/static/upload/goods/'.$img_path;
                $goods['img_name'] = $img_name;
                $price = $price + $goods['price'] * $value->quantity;
                $goods['amount'] = $value->quantity;//该类商品数量
                $goods['other_name'] = $goods['other_name'];
                $goodsInfo[] = $goods;
            }
            else
            {
                echo '商品信息错误';
                return;
            }
        }
        $data['user'] = $user;
        $data['defaultAddressInfo'] = $defaultAddressInfo;
        $data['goodsInfo'] = $goodsInfo;
        $data['price'] = $price;//总价
        $data['base_url'] = $this->base_url;
        $data['content'] = $this->Address_model->getAllAdrressByUid($user->uid);
        // var_dump($data['content']);die;
        $data['goods_id'] = $this->input->get('goods_id');//从订单详情页点击立即购买时会传goods_id
        $data['dataFromGet'] = $this->input->get("data");//用于传递到地址管理
        $data['openid'] = $this->session->openid;//用于判断是支付宝扫码进入还是微信扫码进入
        $this->loadView('header', $data);
        $this->loadView('submit_order');
    }


    /**
     * [提交订单]
     * @return [json] [处理结果]
     */
    public function confirm()
    {
        $time_now = time();
        //session验证并获取user数据
        $user = $this->userSession(false);
        if(! isset($user))
        {
            echo json_encode(array('errcode' => 3, 'errmsg' => '未登录'));
            return;
        }
        $payType = $this->input->post('paytype');//支付方式,1=微信,2=支付宝
        $goods = $this->input->post('goods');//goods为数组
        $leave = $this->input->post('leave');//买家备注
        $address_id = $this->input->post('address_id');//地址id
        isset($leave) || $leave = ''; //买家备注默认为空字符串
        if(! ctype_digit($payType) || empty($goods))
        {
            echo json_encode(array('errcode' => 1, 'errmsg' => '参数错误'));
            return;
        }
        //获取收货地址
        if(isset($address_id))
        {
            $address = $this->Address_model->getAddressByAid($address_id);
        }
        else
        {
            //获取该用户的默认收货地址
            $address = $this->User_model->getDefaultAddressInfoByUid($user->uid);
        }
        if(empty($address))
        {
            echo json_encode(array('errcode' => 4, 'errmsg' => '暂无收获地址，请进行添加'));
            return;
        }
        $address = json_encode($address);
        //订单产品总数量
        $total_amount = 0;
        //订单总价格
        $total_price = 0;
        $order_detail = array();
        //循环获取每个产品的数量、产品信息
        $this->load->model('Goods_model');
        foreach ($goods as $key => $value) {
            if(! ctype_digit($value['goods_id']) || ! ctype_digit($value['quantity']) || $value['quantity'] <= 0)
            {
                echo json_encode(array('errcode' => 1, 'errmsg' => '参数错误'));
                return;
            }
            //校验库存
            //code...
            $goods_detail = $this->Goods_model->getGoodsById($value['goods_id']);
            if(empty($goods_detail) || $goods_detail['status'] != 2)
            {
                echo json_encode(array('errcode' => 5, 'errmsg' => '商品已下架或不存在'));
                return;
            }
            $order_detail[] = array('goods_id' => $value['goods_id'], 
                                    'amount' => $value['quantity'],
                                    'activity_id' => $goods_detail['activity_id'],
                                    'price' => $goods_detail['price'],
                                    'update_time' => $time_now,
                                    'last_return_time' => $time_now,
                                    'status' => 3,//订单详情状态：1=支付成功,2=已发货，3=未支付,4=超时,5=已退押金
                                    );
            $total_amount += $value['quantity'];
            $total_price += $value['quantity'] * $goods_detail['price'];
        }

        if($total_price <= 0 || $total_price > 50000)
        {
            echo json_encode(array('errcode' => 6, 'errmsg' => '总价格必须大于0且小于等于50000'));
            return;
        }
        //生成订单
        $order = array('uid' => $user->uid,
                       'address' => $address,
                       'status' => 3,//订单状态：1=支付成功,2=已发货,3=未支付,4=超时,5=已退押金
                       'sent_amount' => 0,
                       'return_money' => 0,
                       'amount' => $total_amount,
                       'price' => $total_price,
                       'paytype' => $payType,
                       'leave' => $leave,
                       'create_time' => $time_now,
                       'update_time' => $time_now);
        //添加到订单表中
        $orderid = $this->order_model->addOrder($order);
        if($orderid === false)
        {
            echo json_encode(array('errcode' => 2, 'errmsg' => '订单插入失败'));
            return;
        }
        //添加到订单详情表中
        foreach ($order_detail as $key => &$value) {
            $value['order_id'] = $orderid;
            $this->Orderdetail_model->addOrderDetail($value);
        }
        //将order及orderdetail写入redis
        $order['order_id'] = $orderid;
        $redisData['order'] = $order;
        $redisData['order_detail'] = $order_detail;
        $redisData = json_encode($redisData);
        $expire = 30*60;//30分钟
        $this->load->library('RedisDriver', 'redisdriver');
        $this->redisdriver->connect();
        $this->redisdriver->setStr('order_'.$orderid, $redisData, $expire);
        echo json_encode(array('errcode' => 0, 'errmsg' => '订单提交成功', 'orderid' => $orderid));
    }


    //未支付的订单重新发起支付(需要session)
    public function repay()
    {
        $user = $this->userSession(false);
        if(! isset($user))
        {
            echo json_encode(array('errcode' => 3, 'errmsg' => '未登录'));
            return;
        }

        $order_id = $this->input->post('order_id');
        if (!ctype_digit($order_id)) {
            //参数错误
            echo json_encode(array('errcode' => 1, 'errmsg' => '参数错误'));
            return;
        }

        //根据orderid从redis读取订单数据
        $orderData = getOrderFromRedisByOrderid($order_id);
        // var_dump($orderData);die;
        if(empty($orderData))
        {
            //订单不存在
            echo json_encode(array(
                'errcode' => 2,
                'errmsg' => '订单不存在',
            ));
            return;
        }

        //检查订单是否已支付
        $orderDataObj = json_decode($orderData);
        if($orderDataObj->order->status != 3)
        {
            echo json_encode(array('errcode' => 4, 'errmsg' => '订单已支付'));
            return;
        }
        // 校验库存
        //code..
        
        //校验商品是否下架
        $this->load->model('Goods_model');
        foreach($orderDataObj->order_detail as $key => $value)
        {
            $goods_detail = $this->Goods_model->getGoodsById($value->goods_id);
            if(empty($goods_detail) || $goods_detail['status'] != 2)
            {
                echo json_encode(array('errcode' => 5, 'errmsg' => '商品已下架或不存在'));
                return;
            }
        }
        echo json_encode(array(
            'errcode' => 0,
            'errmsg' => '订单存在',
            'data' => $orderData,
        ));
    }

}